package com.android.powerbankpad.audio;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Vibrator;

import com.android.powerbankpad.config.Constants;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.cache.FilePathUtils;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;

/**
 * 播放音频
 */
public class BeepManager implements Closeable {
    private static final String TAG = BeepManager.class.getSimpleName();

    private static final float BEEP_VOLUME = 0.50f;
    private static final long VIBRATE_DURATION = 200L;

    private final Activity activity;
    private MediaPlayer mediaPlayer;

    private boolean playBeep;

    public BeepManager(Activity activity) {
        this.activity = activity;
        updatePrefs();
    }

    private static boolean shouldBeep(Context activity) {
        boolean shouldPlayBeep = true; //prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
        if (shouldPlayBeep) {
            // See if sound settings overrides this
            AudioManager audioService = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
            if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
                shouldPlayBeep = false;
            }
        }
        return shouldPlayBeep;
    }

    public synchronized void updatePrefs() {
        //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        //playBeep = shouldBeep(prefs, activity);
        playBeep = shouldBeep(activity);
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
            // so we now play on the music stream.
            activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
            //mediaPlayer = buildMediaPlayer(activity);


        }
    }

    /**
     * 开启响铃和震动
     *
     * @param playType 1 正常 2 警告 3错误 4入库成功
     */
    @SuppressLint("MissingPermission")
    public synchronized void playBeepSoundAndVibrate(int playType) {
        if (playBeep && mediaPlayer != null) {
            switch (playType) {
                case 1:
                    mediaPlayer.start();
                    break;
            }
        }
    }

    /**
     * 开启震动
     */
    @SuppressLint("MissingPermission")
    private void setViBrate() {
        Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(VIBRATE_DURATION);
    }

    private String getPathAudio(String pathAudio) {
        File d = new File(FilePathUtils.getInstance().getCacheFiles(), CacheUtils.getString(Constants.audio_path));
        if (!d.exists()) {
            d.mkdirs();
        }
        String path = d.getAbsolutePath().concat(pathAudio);
        return path;
    }

    private boolean isFileExites(String pathAudio) {
        File d = new File(FilePathUtils.getInstance().getCacheFiles(), CacheUtils.getString(Constants.audio_path));
        if (!d.exists()) {
            d.mkdirs();
        }
        String path = d.getAbsolutePath().concat(pathAudio);
        return FilePathUtils.getInstance().fileIsExists(path);

    }


    public void startAudio(String type) {
        String audioUrl = "";
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        try {
            if (isFileExites(type)) {
                LogcatUtils.e("  startAudio 播放音频  " + type);
                audioUrl = getPathAudio(type);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                Uri uri = Uri.parse(audioUrl);
                mediaPlayer.setDataSource(activity, uri);
                mediaPlayer.prepare();
                mediaPlayer.start();
            }
            /*else {
                LogcatUtils.e("  startAudio 本地音频  "+type);
                switch (type) {
                    case Constants.rent_success:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.rent_success_zh;
                        break;
                    case Constants.rent_fail:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.rent_fail_zh;
                        break;
                    case Constants.return_success:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.return_success_zh;
                        break;
                    case Constants.return_fail:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.return_fail_zh;
                        break;
                    case Constants.networking_success:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.networking_success_zh;
                        break;
                    case Constants.networking_fail:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.networking_fail_zh;

                        break;
                    case Constants.boot_strap:
                        audioUrl = "android.resource://com.android.powerbankpad/" + R.raw.boot_strap_zh;
                        break;
                    default:
                        break;
                }
            }*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 设置音量


    }

    public void setBeepVolume(int vol) {
        //音量控制
        AudioManager mAudioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        //最大音量 
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        double i = vol / 100d;
        int volume = (int) (maxVolume * i);
        LogcatUtils.d("LogcatUtils  MainActivity 音量大小 volume::  " + volume);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
    }


    @Override
    public synchronized void close() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;

        }
    }

}
